import { Shape, Vector2 } from "three";
import {
  KujialeParamModel,
  KujialePath,
  type KujialeResultLine,
} from "../types/KujialeJsonModels/KujialeParamModel";
import { getArc2Angle, getArcCenter, getEllArc2Angle } from "../math";

export const DrawPathShape = (model: KujialeParamModel): Shape => {
  const { path, holes } = getShapeData(model);
  const { resultLines: lines, resultPoints: points } = path;
  const shape = getShape(points, lines);

  if (holes) {
    shape.holes = holes.map((hole) =>
      getShape(hole.resultPoints, hole.resultLines)
    );
  }

  return shape;
};

export function getShapeData(model: KujialeParamModel) {
  const { path, holes } = model.paramPlankPath!;
  return { path, holes } as unknown as {
    path: KujialePath;
    holes: KujialePath[];
  };
}

export function getShape(points: Vector2[], lines: KujialeResultLine[]): Shape {
  const shape = new Shape();

  const [startPoint, ...otherPoints] = points;
  if (points.length === lines.length) otherPoints.push(startPoint);

  shape.moveTo(startPoint.x, startPoint.y);
  otherPoints.forEach((point, index) => {
    const line = lines[index];
    const get2p = () => {
      const p1 = points[index];
      const p2 = point;
      return [p1, p2];
    };
    // const getLine = () => line as ILineData2;
    switch (line.type) {
      case 0: //ELineType.SEGMENT
        shape.lineTo(point.x, point.y);
        break;
      // 圆弧还原逻辑
      case 1: //ELineType.CIRCLE_ARC:
        {
          const [p1, p2] = get2p();
          const { minorArc, clockwise, radius } = line;
          const center = getArcCenter(p1, p2, radius!, minorArc!, !clockwise);
          const [startAngle, endAngle] = getArc2Angle(center, p1, p2);
          const { x: cx, y: cy } = center;
          shape.absarc(cx, cy, radius!, startAngle, endAngle, clockwise);
        }
        break;
      // // 椭圆弧还原逻辑
      // case 2://ELineType2.ELLIPSE_ARC:
      //   {
      //     const [p1, p2] = get2p();
      //     const {
      //       clockwise,
      //       curve2d,
      //       curve2d: { a, b, c },
      //     } = line;
      //     const { x: cx, y: cy } = c;
      //     const [startAngle, endAngle] = getEllArc2Angle(
      //       p1,
      //       p2,
      //       !clockwise,
      //       curve2d
      //     );
      //     shape.absellipse(cx, cy, a, b, startAngle, endAngle, clockwise, 0);
      //   }
      //   break;

      default:
        shape.lineTo(point.x, point.y);
        break;
    }
  });
  return shape;
}
